<template>
  <div class="container">
    <el-card :border="false" style="margin-bottom: 15px;">
      <el-form :inline="true">
        <!-- 这是那个头部 -->
        <div class="items-center">
          <StatisticCard style="width: 60%;"/>
          <el-button class="ml-5 bg-green-500 text-white px-4 py-1 rounded hover:bg-green-600" @click="AddTeam">添加团队
          </el-button>
        </div>
      </el-form>
    </el-card>
    <!-- 内容部分 -->
    <el-card :border="false">
      <div class="container_bottom">
        <el-table :data="tableData" :preserve-expanded-content="true" border style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <p :style="{ margin: '10px' }"> 团队成员个数: {{ props.row.Members.length }}</p>
                <h3 :style="{ margin: '10px' }"> 团队成员详情</h3>
                <el-button :style="{ marginLeft: '10px' }" plain size="small" type="success"
                  @click="viewTeamProject(props.row)">查看团队项目
                </el-button>
                <el-table :border="true" :data="props.row.Members">
                  <el-table-column label="成员ID" prop="User.id" width="100px" />
                  <el-table-column label="用户名" prop="User.username" />
                  <el-table-column label="联系电话" prop="User.phone" />
                  <el-table-column label="成员角色">
                    <template #default="scope">
                      <span v-if="scope.row.User.id === props.row.Team.captain_user_id" style="color: red;">团队队长</span>
                      <span v-else style="color: green;">普通成员</span>
                    </template>
                  </el-table-column>
                  <!-- 新增的条件列 -->
                  <el-table-column v-if="isCaptain(props.row)" label="操作" prop="captainInfo">
                    <template #default="scope">
                      <div class="center-button">
                        <el-button size="small" type="danger" @click="handleRemoveMember(scope.row, props.row)"
                          :disabled="scope.row.User.id === props.row.Team.captain_user_id">移除成员
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="团队ID" prop="Team.id" />
          <el-table-column label="团队名称" prop="Team.name" />
          <el-table-column label="通讯地址" prop="Team.address">
            <template v-slot="scope">
              {{ shortenUrl(scope.row.Team.address) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300px">
            <template #default="scope">
              <template v-if="isCaptain(scope.row)">
                <el-button size="small" type="primary" @click="handleCreateProject(scope.row)">新建项目</el-button>
                <el-button size="small" type="success" @click="handleInviteMember(scope.row)">邀请成员</el-button>
                <el-button size="small" type="warning" @click="view(scope.row)">查看</el-button>
              </template>
              <template v-else>
                <div class="center-button">
                  <el-button size="small" type="warning" @click="view(scope.row)">查看</el-button>
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="width: 100%; align-items: center;justify-content: center;margin-top: 20px;">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30]"
            :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
      </div>
    </el-card>
    <!-- 添加团队表单 -->
    <!-- <UserTeamDialogForm ref="teamFormDialog" /> -->
    <TeamFormDialog ref="teamFormDialog" />
    <!-- 查阅表单 -->
    <el-dialog v-model="dialogVisible" title="团队信息" width="500px">
      <el-form label-width="100px">
        <el-form-item label="团队ID">
          <el-input v-model="formData.Team.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="团队名称">
          <el-input v-model="formData.Team.name" readonly></el-input>
        </el-form-item>
        <el-form-item label="通讯地址">
          <el-input v-model="formData.Team.address" readonly></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新建项目表单 -->
    <ProjectFormDialog ref="projectFormDialog" />
    <!-- 邀请成员表单 -->
    <InviteMember ref="inviteMemberDialog" />
    <!-- 查看团队项目表单 -->
    <ShowTeamProjectMsg ref="showTeamProjectMsg" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import TeamFormDialog from '../components/form/UserTeamForm.vue';
import ProjectFormDialog from '../components/form/AddNewProject.vue';
import InviteMember from '../components/form/InviteMember.vue';
import ShowTeamProjectMsg from '../components/form/ShowTeamProjectMsg.vue';
import StatisticCard from '../components/StatisticCard.vue';
import { ElMessage, ElMessageBox } from "element-plus";
import axios from '../http/index.js'

const currentPage = ref(1)
const pageSize = ref(10)
//记录请求返回数据的集合
const msg = ref([]);
//用于保存当前用户信息
const userInfo = ref()
//用于记录用户所查询的输入信息 inputStr
const inputStr = ref()

//用于暂存当前页的数据
const tableData = ref([])
tableData.value = msg.value
let total = ref(0)

// 获取所有的数据
function getData() {
  axios.get('team/getResource')
    .then(response => {
      if (response.code === 1) {
        // 请求成功的处理
        msg.value = response.teams;
        console.log("msg.value:", msg.value);
        userInfo.value = response.user;
        // 获取数据的总条数
        total.value = Array.isArray(msg.value) ? msg.value.length : 0;
        // 获取当前页的数据
        getPageData();
        console.log("当前页的数据:", tableData.value);
        ElMessage({
          message: '查询数据加载成功',
          type: 'success'
        });
      } else {
        ElMessage({
          message: '查询数据加载失败',
          type: 'error'
        });
      }
    })
    .catch(err => {
      // 请求失败的处理
      ElMessage({
        message: '查询数据加载失败: ' + err.message,
        type: 'error'
      });
      console.error(err);
    });
}

//获取全部数据
function getAllData() {
  console.log('getAllData')
  //清空输入的imputStr
  //请求全部的数据
  getData()
}

//获取当前页的数据
function getPageData() {
  //先把当前页面的数据清空
  tableData.value = []
  //获取当前页面的数据
  for (let i = (currentPage.value - 1) * pageSize.value; i < total.value; i++) {
    //遍历数据添加到tableData中
    tableData.value.push(msg.value[i])
    //判断是否达到一页的要求
    if (tableData.value.length === pageSize.value) break
  }
}

//分页时修改每一页所展示的数据量
const handleSizeChange = (val) => {
  //修改当前每一页的数据条数
  pageSize.value = val
  //数据重新分页
  getPageData()
  console.log(`${val} items per page`)
}

//调整当前页的页码
const handleCurrentChange = (val) => {
  //修改当前页的页码
  currentPage.value = val
  //数据重新分页
  getPageData()
  console.log(`current page: ${val}`)
}

// 添加团队的按钮点击事件
const teamFormDialog = ref(null); // 创建一个引用
const AddTeam = () => {
  teamFormDialog.value.openDialog(); // 调用子组件的 openDialog 方法
};

// 截断链接函数
const shortenUrl = (url) => {
  return url.length > 30 ? url.substring(0, 30) + '...' : url;
};

// 检查是否是团队队长
function isCaptain(row) {
  return userInfo.value && row.Team && userInfo.value.id === row.Team.captain_user_id;
}

const dialogVisible = ref(false); // 控制对话框显示与隐藏的变量
const formData = ref({}); // 用于存储表单数据
// 控制对话框显示与隐藏的函数
const view = (data) => {
  formData.value = data; // 将传入的数据赋值给 formData
  dialogVisible.value = true; // 显示对话框
};

//添加项目表单
const projectFormDialog = ref(null);
// 处理新建项目按钮点击事件
const handleCreateProject = (row) => {
  // 假设 row 中包含 team_id，将其传递给子组件
  const teamId = row.Team.id; // 替换为实际的 team_id 字段路径
  projectFormDialog.value.openDialog(teamId); // 调用子组件的 openDialog 方法，并传递 teamId
};
//查看项目表单
const showTeamProjectMsg = ref(null);

async function viewTeamProject(row) {
  console.log("查看项目的按钮被点击了", row.Team.id)
  await axios.get('team/manageTeam', {
    params: {
      team_id: row.Team.id
    }
  })
    .then(response => {
      if (response.code === 1) {
        // 请求成功的处理
        console.log("查看项目的按钮被点击了", response);
        console.log("查看项目的按钮被点击了", response.project.name, response.project.git_address);
        showTeamProjectMsg.value.openDialog(response); // 调用子组件的 openDialog 方法，并传递数据
      } else {
        ElMessage({
          message: '查询项目失败',
          type: 'error'
        });
      }
    })
    .catch(err => {
      // 请求失败的处理
      ElMessage({
        message: '查询数据加载失败: ' + err.message,
        type: 'error'
      });
      console.error(err);
    });
}


// 处理移除成员按钮点击事件
// 处理移除成员按钮点击事件
function handleRemoveMember(member, team) {
  // 弹出确认框
  ElMessageBox.confirm(
    `确定要将成员 ${member.User.username} 从团队 ${team.Team.name} 中移除吗？`, // 确认框内容
    '确认操作', // 确认框标题
    {
      confirmButtonText: '确定', // 确认按钮文本
      cancelButtonText: '取消', // 取消按钮文本
      type: 'warning' // 确认框类型（警告类型）
    }
  )
    .then(() => {
      // 用户点击确认后执行的操作
      axios.post('team/drop', {
        team_id: team.Team.id,
        user_id: member.User.id
      })
        .then(response => {
          if (response.code === 1) { // 假设后端返回的数据在 response.data 中
            // 请求成功的处理
            ElMessage({
              message: response.message,
              type: 'success'
            });
            getData(); // 刷新数据
          } else {
            ElMessage({
              message: '移除成员失败: ' + response.message,
              type: 'error'
            });
          }
        })
        .catch(err => {
          // 请求失败的处理
          ElMessage({
            message: '移除成员失败: ' + err.message,
            type: 'error'
          });
          console.error(err);
        });
    })
    .catch(() => {
      // 用户点击取消时的处理
      ElMessage({
        message: '已取消移除成员操作',
        type: 'info'
      });
    });
}
// 处理邀请成员按钮点击事件
const inviteMemberDialog = ref(null); // 创建一个引用
function handleInviteMember(row) {
  inviteMemberDialog.value.openDialog(row); // 调用子组件的 openDialog 方法，并传递
};


onMounted(() => {

  getData()

})


</script>

<style scoped>
.container {
  width: 100% !important;
}

.items-center {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.center-button {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  /* 使容器占满整个单元格的高度 */
}
</style>


<script>
export default {
  name: 'UserTeamManagement',
};
</script>